package com.tzpay.tzpay.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dtr.zxing.activity.CaptureActivity;
import com.tzpay.tzpay.R;
import com.tzpay.tzpay.common.PayType;
import com.tzpay.tzpay.threadpool.AsyncTaskExecutors;
import com.tzpay.tzpay.ui.BaseActivity;
import com.tzpay.tzpay.utils.AnimationUtil;
import com.tzpay.tzpay.utils.SPUtil;
import com.tzpay.tzpay.utils.T;
import com.tzpay.tzpay.utils.Utils;
import com.tzpay.tzpay.view.KeyboardView;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by chenfeiyue on 16/4/7.
 */
public class AcquiringActivity extends BaseActivity {

    @Bind(R.id.tv_pay_input_hint)
    TextView tvPayInputHint;
    @Bind(R.id.numTV)
    public TextView numTV;
    @Bind(R.id.linear_amount)
    LinearLayout linearAmount;
    @Bind(R.id.alipay_ll)
    LinearLayout alipayLl;
    @Bind(R.id.baidu_ll)
    LinearLayout baiduLl;
    @Bind(R.id.wechat_ll)
    LinearLayout wechatLl;
    @Bind(R.id.pay_v_keyboard)
    KeyboardView keyboardView;

    @Bind(R.id.bestpay_ll)
    LinearLayout bestpay_ll;
    @Bind(R.id.bestpay_iv)
    ImageView bestpay_iv;

    private String num1 = "0";
    private String num2 = "0";
    private String num3 = "0";
    private String num = "";
    private int setCursor = YUAN;
    private int delCursor = YUAN;
    private final static int CLEAR = 0;
    private final static int YUAN = 1;
    private final static int JIAO = 2;
    private final static int FEN = 3;
    private boolean startDel;
    private int paymentAmountInt;// 支付金额
    private final String PAYMENT_TYPE_ALIPAY = "alipay";
    private final String PAYMENT_TYPE_WECHAT = "wechat";
    private final String PAYMENT_TYPE_BAIDU = "baidu";
    private final String PAYMENT_TYPE_BESTPAY = "bestpay";

    private String paymentType = "swipe";// 支付方式选择 1、alipay 2、wechat 3、swipe

    private int pay_type = PayType.PAY_SCAN; // 支付类型 1、扫一扫， 2、付款码


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        pay_type = getIntent().getIntExtra(PayType.PAY_YEPE, PayType.PAY_SCAN);
        // 初始化view
        initView();
        setHasAppBar(false);
    }

    @Override
    public void setupContentView() {
        setContentView(R.layout.activity_acquiring);
    }

    private void initData() {
        num1 = "0";
        num2 = "0";
        num3 = "0";
        num = "";
        setCursor = YUAN;
        delCursor = YUAN;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick(R.id.iv_close_btn)
    public void onCloseBtnClick() {
        finish();
    }

    /**
     * 初始化操作
     */
    private void initView() {
        keyboardView.setKeyboardListener(keyboardClickListener);
        alipayLl.setOnClickListener(listener);
        baiduLl.setOnClickListener(listener);
        wechatLl.setOnClickListener(listener);
        bestpay_ll.setOnClickListener(listener);
    }

    private boolean isStillTouchDelBtn() {
        return false;
    }


    /**
     * 点击后微信或者支付宝按钮后的跳转
     */
    private void startPay() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int amountInt = Integer.parseInt(num1) * 100 + Integer.parseInt(num2) * 10 + Integer.parseInt(num3);
                paymentAmountInt = amountInt;
                if (amountInt == 0) {
                    // 没有输入金额就震动金额
                    linearAmount.requestFocus();
                    AnimationUtil.shake(AcquiringActivity.this, linearAmount);
                    return;
                }

                // 根据用户点击支付类型，进入到不同的支付方法
                switch (paymentType) {
                    case PAYMENT_TYPE_ALIPAY: // 支付宝支付
                        AcquiringActivity.this.startAliPay();
                        break;
                    case PAYMENT_TYPE_WECHAT: // 微信支付
                        AcquiringActivity.this.startWeXinPay();
                        break;
                    case PAYMENT_TYPE_BAIDU: //百度钱包支付
                        AcquiringActivity.this.startBaiDuPay();
                        break;
                    case PAYMENT_TYPE_BESTPAY:
                        AcquiringActivity.this.startBestPay();
                        break;
                }
            }
        });
    }

    private void deleteAmount() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                numTV.setText(num);
                // 改变提交按钮和支付宝按钮背景
                AcquiringActivity.this.changeSubmitButtonAndAlipayLayoutBackground();
            }
        });
    }

    /**
     * 删除金额
     */
    private void delAccount() {
        if (startDel) {
            AsyncTaskExecutors.executeTask((Runnable) new Runnable() {
                @Override
                public void run() {
                    // 按下就删除一个数字
                    AcquiringActivity.this.delNum();
                    // 开始删除的时间
                    long startTime = System.currentTimeMillis() + 500;
                    while (true) {
                        if (!startDel) {
                            break;
                        }
                        if ((System.currentTimeMillis() - startTime) > 100) {
                            AcquiringActivity.this.delNum();
                            startTime = System.currentTimeMillis();
                        }
                    }
                }
            });
        }
    }


    /**
     * 震动方法
     */
    private void vibrateMethod() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        long[] pattern = {10, 30};
        vibrator.vibrate(pattern, -1);
    }

    /**
     * 处理支付操作
     */
    private void dealPaymentOperate() {
        // 无网就弹出框提示
        if (!Utils.isCanConnectionNetWork(AcquiringActivity.this)) {
            showNoNetWorkDialog();
            return;
        }
        startPay();
    }

    private KeyboardView.KeyboardClickListener keyboardClickListener = new KeyboardView.KeyboardClickListener() {
        @Override
        public void clickButton(String number) {
            linearAmount.setVisibility(View.VISIBLE);
            tvPayInputHint.setVisibility(View.INVISIBLE);
            vibrateMethod();
            setNum(number);
        }

        @Override
        public void clickDelDown() {
            tvPayInputHint.setVisibility(View.INVISIBLE);
            linearAmount.setVisibility(View.VISIBLE);
            startDel = true;
            vibrateMethod();
            // 删除金额
            delAccount();
        }

        @Override
        public void clickDelUp() {
            tvPayInputHint.setVisibility(View.INVISIBLE);
            linearAmount.setVisibility(View.VISIBLE);
            startDel = false;
        }

        @Override
        public void clickPoint() {
            tvPayInputHint.setVisibility(View.INVISIBLE);
            linearAmount.setVisibility(View.VISIBLE);
            vibrateMethod();
            if (setCursor != CLEAR) {
                setCursor = JIAO;
            }
        }
    };
    /**
     * 点击刷卡触发的事件
     */
    private OnClickListener listener = new OnClickListener() {

        public void onClick(View paramView) {
            tvPayInputHint.setVisibility(View.INVISIBLE);
            linearAmount.setVisibility(View.VISIBLE);
            switch (paramView.getId()) {
                case R.id.alipay_ll:
                    paymentType = PAYMENT_TYPE_ALIPAY;
                    break;
                case R.id.wechat_ll:
                    paymentType = PAYMENT_TYPE_WECHAT;
                    break;
                case R.id.baidu_ll:
                    paymentType = PAYMENT_TYPE_BAIDU;
                    break;

                case R.id.bestpay_ll:
                    paymentType = PAYMENT_TYPE_BESTPAY;
                    break;

            }
            String amountString = numTV.getText().toString();
            linearAmount.requestFocus();
            if (!amountString.equalsIgnoreCase("0.00")) {
                // 处理支付操作
                dealPaymentOperate();
            } else {// 没有输入金额就震动金额
                if (linearAmount.isShown()) {
                    linearAmount.requestFocus();
                    AnimationUtil.shake(AcquiringActivity.this, linearAmount);
                }
            }
        }
    };

    private void setNum(String number) {
        switch (setCursor) {
            case CLEAR:
                break;
            case YUAN:
                if (num1.equalsIgnoreCase("0")) {
                    num1 = number;
                } else {
                    if (getNum1Length() < 6) {
                        num1 = num1 + number;
                    }
                    delCursor = YUAN;
                }
                break;
            case JIAO:
                num2 = number;
                delCursor = JIAO;
                setCursor = FEN;
                break;
            case FEN:
                if (!number.equals("0")) {
                    num3 = number;
                    setCursor = CLEAR;
                    delCursor = FEN;
                } else {
                    if (num1.equals("0") && num2.equals("0")) {
                        delCursor = FEN;
                    } else {
                        setCursor = CLEAR;
                        delCursor = FEN;
                    }
                }
                break;
            default:
                break;
        }
        num = num1 + "." + num2 + num3;
        deleteAmount();
    }

    private void delNum() {
        switch (delCursor) {
            case CLEAR:
                num1 = "0";
                delCursor = 0;
                break;
            case YUAN:
                delCursor = YUAN;
                if (num1.length() == 2) {
                    delCursor = CLEAR;
                }
                if (getNum1Length() > 1) {
                    num1 = num1.substring(0, getNum1Length() - 1);
                } else {
                    num1 = "0";
                    delCursor = CLEAR;
                }
                setCursor = YUAN;
                break;
            case JIAO:
                num2 = "0";
                delCursor = YUAN;
                setCursor = JIAO;
                break;
            case FEN:
                num3 = "0";
                delCursor = JIAO;
                setCursor = FEN;
                break;
            default:
                break;
        }
        num = num1.substring(0, getNum1Length()) + "." + num2 + num3;
        deleteAmount();
    }

    private int getNum1Length() {
        return num1.length();
    }

    /**
     * 改变提交按钮和支付宝按钮背景
     */
    private void changeSubmitButtonAndAlipayLayoutBackground() {
        if (num1.equals("0") && num2.equals("0") && num3.equals("0")) {
//            alipayIv.setBackgroundResource(R.drawable.ic_alipay_bottom_gray);
//            wechatLl.setBackgroundResource(R.color.main_gray_press);
//            baiduIv.setBackgroundResource(R.drawable.ic_baidu_bottom_gray);

            bestpay_ll.setBackgroundResource(R.color.main_gray_press);
            bestpay_iv.setAlpha(0.4f);
        } else {
//            alipayIv.setBackgroundResource(R.drawable.ic_alipay_bottom);
//            wechatLl.setBackgroundResource(R.drawable.selector_wchat_main);
//            baiduIv.setBackgroundResource(R.drawable.ic_baidu_bottom);

            bestpay_ll.setBackgroundResource(R.drawable.selector_bestpay_main);
            bestpay_iv.setAlpha(1.0f);
        }
    }


    public void onResume() {
        super.onResume();
        if (spUtil.getBoolean(SPUtil.SPKey.IS_PAY_SUCCESS, false)) {
            initData();
            numTV.setText("0.00");
            linearAmount.setVisibility(View.GONE);
            tvPayInputHint.setVisibility(View.VISIBLE);
            paymentAmountInt = 0;
            spUtil.save(SPUtil.SPKey.IS_PAY_SUCCESS, false);
        }
        // 改变提交按钮和支付宝按钮背景
        changeSubmitButtonAndAlipayLayoutBackground();
    }


    @Override
    protected void onDestroy() {
        //取消监听网络数据
        super.onDestroy();
    }

    /**
     * 开始支付宝二维码收款
     */
    private void startAliPay() {
//        Intent intent = null;
//        if (spUtil.getInt(SpKey.ALIPAY_TYPE.key, ConstValue.ALIPAY_QRCODE_PAY) == ConstValue.ALIPAY_QRCODE_PAY) {
//            intent = AlipayQrcodeActivity.getCallIntent(this, num);
//        } else {
//            intent = CaptureActivity.getAliPayCallIntent(this, num);
//        }
//        startActivity(intent);
    }

    /**
     * 开始微信支付
     */
    private void startWeXinPay() {
//        Intent intent = null;
//        if (spUtil.getInt(SPUtil.SPKey.WECHAT_PAY_TYPE.key, ConstValue.WE_CHAT_SWING_CARD_PAY) == ConstValue.WE_CHAT_SWING_CARD_PAY) {
//            intent = CaptureActivity.getWeiXinPayCallIntent(this, num);
//        } else {
//            intent = WeChatQrcodeActivity.getCallIntent(this, num);
//        }
//        startActivity(intent);
    }

    /**
     * 百度支付
     */
    private void startBaiDuPay() {
//        Intent intent = new Intent();
//        intent.putExtra("amount", num);
//        intent.setClass(this, BaiduQrcodeActivity.class);
//        startActivity(intent);
    }

    private void startBestPay() {
        T.e("AcquiringActivity", "------------> startBestPay()");
        Intent intent = new Intent();
        intent.putExtra("amount", num);
        intent.putExtra("paymentAmountInt", paymentAmountInt);
        switch (pay_type){
            case PayType.PAY_SCAN:
                intent.setClass(AcquiringActivity.this, CaptureActivity.class);
                break;
            case PayType.PAY_BARCODE:
                intent.setClass(AcquiringActivity.this, CaptureActivity.class);
                break;
            default:
                break;
        }
        startActivity(intent);
    }
}